package com.yugao.fintech.antelope.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yugao.fintech.antelope.auth.AuthApi;
import com.yugao.fintech.antelope.base.log.OperateLog;
import com.yugao.fintech.antelope.base.log.enums.BusinessType;
import com.yugao.fintech.antelope.base.model.constants.SecurityCons;
import com.yugao.fintech.antelope.base.model.constants.ValidationCons;
import com.yugao.fintech.antelope.base.model.enums.BoolEnum;
import com.yugao.fintech.antelope.base.ram.ActionType;
import com.yugao.fintech.antelope.base.ram.RamResource;
import com.yugao.fintech.antelope.system.assembly.SysUserAssembly;
import com.yugao.fintech.antelope.system.model.entity.SysUser;
import com.yugao.fintech.antelope.system.model.rqrs.dept.DeptResp;
import com.yugao.fintech.antelope.system.model.rqrs.dept.DeptTreeDept;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.SelectLoginTenantReq;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.TenantUserAddReq;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.TenantUserResp;
import com.yugao.fintech.antelope.system.service.SysDeptService;
import com.yugao.fintech.antelope.system.service.SysRoleService;
import com.yugao.fintech.antelope.system.service.SysTenantUserService;
import com.yugao.fintech.framework.core.response.PageData;
import com.yugao.fintech.framework.core.response.Resp;
import com.yugao.fintech.framework.mybatisplus.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "用户管理")
@RestController
@Validated
@RequestMapping("/tenantMember")
public class SysTenantMemberController {
    @Autowired
    private SysTenantUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private AuthApi authApi;
    @Autowired
    private SysUserAssembly userAssembly;

    /**
     * 查询全部租户用户数据
     */
    @GetMapping("/pageAllMember")
    @OperateLog
    @RamResource(action = "sys:tenantMember:queryAll", name = "查询全部租户成员数据", type = ActionType.READ)
    public Resp<IPage<TenantUserResp>> pageAllTenantMember(UserPageReq req) {
        IPage<TenantUserResp> page = userService.pageAllTenantUser(req);
        return Resp.ok(page);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/pageMember")
    @OperateLog
    @RamResource(action = "sys:tenantMember:query", name = "查询租户成员", type = ActionType.READ)
    public Resp<IPage<UserResp>> pageUser(UserPageReq req) {
        IPage<UserResp> page = userService.pageUser(req);
        return Resp.ok(page);
    }

    /**
     * 根据用户角色查询用户
     */
    @GetMapping("/listRoleUser")
    @RamResource(action = "sys:tenantMember:listRoleUser", name = "查询角色中的租户成员", type = ActionType.READ)
    public Resp<PageData<UserResp>> listRoleUser(RoleUserListReq req) {
        PageUtil.startPage();
        List<UserResp> list = userService.listRoleUser(req);
        return PageUtil.getDataTable(list);
    }

    /**
     * 查询部门用户
     */
    @GetMapping("/pageDeptUser")
    @RamResource(action = "sys:tenantMember:queryDeptUser", name = "查询部门中的租户成员", type = ActionType.READ)
    public Resp<IPage<DeptUserResp>> pageDeptUser(DeptUserPageReq req) {
        IPage<DeptUserResp> list = userService.pageDeptUser(req);
        return Resp.ok(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RamResource(action = "sys:tenantMember:query", name = "查询租户成员", type = ActionType.READ)
    @GetMapping(value = { "/getUserDetails"})
    public Resp<UserDetailsResp> getUserDetails(@RequestParam(value = "userId", required = false) @NotNull(message = ValidationCons.NOT_EMPTY)
                                                    Long userId) {
        UserResp user = userService.getUserById(userId);
        UserDetailsResp resp = userAssembly.toUserDetailsResp(user);
        resp.setDeptList(deptService.listUserDept(new UserDeptListReq(userId)));
        return Resp.ok(resp);
    }

    @GetMapping("/getById")
    @RamResource(action = "sys:tenantMember:query", name = "查询租户成员", type = ActionType.READ)
    public Resp<UserResp> getById(@RequestParam(value = "id") Long userId) {
        return Resp.ok(userService.getUserById(userId));
    }

    /**
     * 修改用户
     */
    @OperateLog(summary = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @RamResource(action = "sys:tenantMember:update", name = "更新租户成员", type = ActionType.WRITE)
    public Resp<?> update(@Validated @RequestBody UserUpdateReq req) {
        SysUser user = userAssembly.toUser(req);
        userService.checkUserAllowed(user.getUserId());
        // user.setUpdateBy(SecurityUtils.getUserName());

        // 判断用户的角色或者部门是否已经发生变更, 如果发生变更, 则直接强制用户登录
        List<Long> oldRoleIds = roleService.listRoleIdsByUserId(user.getUserId());
        List<Long> newRoleIds = user.getRoleIds();
        if (!CollectionUtils.isEqualCollection(oldRoleIds, newRoleIds)) {
            boolean updateResult = userService.updateById(user);
            // 这快直接将用户密码设置为空即可, 下次调用接口权限校验时候
            authApi.removeAccessTokenByUserId(user.getUserId());
            return updateResult ? Resp.ok() : Resp.fail("更新失败");
        }

        List<Long> oldDeptIds = deptService.listUserDept(new UserDeptListReq(user.getUserId()))
                .stream().map(DeptResp::getId).collect(Collectors.toList());
        List<Long> newDeptIds = user.getDeptIds();
        if (!CollectionUtils.isEqualCollection(oldDeptIds, newDeptIds)) {
            boolean updateResult = userService.updateById(user);
            authApi.removeAccessTokenByUserId(user.getUserId());
            return updateResult ? Resp.ok() : Resp.fail("更新失败");
        }
        return userService.updateById(user) ? Resp.ok() : Resp.fail("更新失败");
    }


    @ApiOperation(value = "移除租户用户")
    @OperateLog(summary = "租户用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    @RamResource(action = "sys:tenantMember:delete", name = "删除租户成员", type = ActionType.WRITE)
    public Resp<?> delete(@RequestParam(value = "id") Long userId) {
        userService.deleteUserByIds(Collections.singletonList(userId));
        return Resp.ok();
    }

    /**
     * 查询指定用户和部门关联的数据 (树)
     */
    @GetMapping(value = "/listUserDeptTree")
    @RamResource(action = "sys:tenantMember:listUserDept", name = "查询租户成员部门", type = ActionType.READ)
    public Resp<List<DeptTreeDept>> listUserDeptTree(@RequestParam(value = "userId") String userId) {
        List<DeptResp> deptList = this.userService.listUserDept(Long.parseLong(userId));
        List<DeptResp> deptRespList = deptService.buildDeptTree(deptList);
        return Resp.ok(deptRespList.stream().map(DeptTreeDept::new).collect(Collectors.toList()));
    }

    /**
     * 查询指定用户和部门关联的数据
     */
    @GetMapping(value = "/listUserRole")
    @RamResource(action = "sys:tenantMember:listUserRole", name = "查询用户角色", type = ActionType.READ)
    public Resp<List<String>> listUserRole(@RequestParam(value = "userId") String userId) {
        List<String> roleList = this.roleService.listRoleIdsByUserId(Long.parseLong(userId))
                .stream().map(String::valueOf).collect(Collectors.toList());
        return Resp.ok(roleList);
    }

    @RamResource(action = "sys:tenantMember:query", name = "查询用户", type = ActionType.READ)
    @GetMapping(value = "/user/listUserByIds", headers = SecurityCons.HEADER_FROM_IN)
    public Resp<List<UserResp>> listUserByIds(@RequestParam(value = "userIds") List<Long> userIds) {
        return Resp.ok(userService.listUserByIds(userIds));
    }

    /**
     * 回收站
     */
    @RamResource(action = "sys:tenantMember:recycleBin", name = "查询回收站中的用户", type = ActionType.READ)
    @GetMapping(value = "/recycleBin")
    public Resp<IPage<UserResp>> recycleBin() {
        UserPageReq query = new UserPageReq();
        query.setDelFlag(BoolEnum.TRUE.getCode());
        IPage<UserResp> list = userService.pageUser(query);
        return Resp.ok(list);
    }

    @ApiOperation(value = "为租户分配用户")
    @PostMapping("/assignUser")
    @RamResource(action = "sys:tenantMember:assign", name = "添加租户成员", type = ActionType.READ)
    public Resp<?> tenantMember(@RequestBody TenantUserAddReq req) {
        userService.assignUser(req);
        return Resp.ok();
    }

    /**
     * 登录成功之后, 选择租户后会调用该接口
     */
    @ApiOperation(value = "选择登录的租户")
    @PostMapping("/selectLoginTenant")
    public Resp<?> selectLoginTenant(@RequestBody @Validated SelectLoginTenantReq req) {
        return Resp.ok(userService.selectLoginTenant(req));
    }

}